import 'package:state_management_redux/shopping_list/shopping_item.dart';
import 'package:state_management_redux/shopping_list/shopping_list_state.dart';

import 'shopping_list_action.dart';

ShoppingListState shoppingListReducer(ShoppingListState state, action) {
  if (action is AddItemAction) {
    var newItems = addItemActionHandler(state.shoppingItems, action.item);
    return ShoppingListState(shoppingItems: newItems);
  }
  if (action is ToggleItemStateAction) {
    var newItems =
        toggleItemStateActionHandler(state.shoppingItems, action.item);

    return ShoppingListState(shoppingItems: newItems);
  }
  if (action is ReadOfflineSuccessAction) {
    return ShoppingListState(shoppingItems: action.items);
  }
  if (action is AddItemCountAction) {
    var newItems = addItemCountActionHandler(state.shoppingItems, action.item);

    return ShoppingListState(shoppingItems: newItems);
  }
  if (action is SubItemCountAction) {
    var newItems = subItemCountActionHandler(state.shoppingItems, action.item);

    return ShoppingListState(shoppingItems: newItems);
  }

  return state;
}

List<ShoppingItem> addItemActionHandler(
    List<ShoppingItem> oldItems, ShoppingItem newItem) {
  List<ShoppingItem> newItems = [];

  if (oldItems.length > 0) {
    bool duplicated = false;
    newItems = oldItems.map((item) {
      if (item == newItem) {
        duplicated = true;
        return ShoppingItem(
            name: item.name, selected: item.selected, count: item.count + 1);
      }
      return item;
    }).toList();
    if (!duplicated) {
      newItems.add(newItem);
    }
  } else {
    newItems.add(newItem);
  }

  return newItems;
}

List<ShoppingItem> toggleItemStateActionHandler(
    List<ShoppingItem> oldItems, ShoppingItem newItem) {
  List<ShoppingItem> newItems = oldItems.map((item) {
    if (item == newItem)
      return ShoppingItem(
          name: item.name, selected: !item.selected, count: item.count);
    return item;
  }).toList();

  return newItems;
}

List<ShoppingItem> addItemCountActionHandler(
    List<ShoppingItem> oldItems, ShoppingItem itemToHandle) {
  List<ShoppingItem> newItems = oldItems.map((item) {
    if (item == itemToHandle) {
      return ShoppingItem(
          name: item.name, selected: item.selected, count: item.count + 1);
    } else {
      return item;
    }
  }).toList();

  return newItems;
}

List<ShoppingItem> subItemCountActionHandler(
    List<ShoppingItem> oldItems, ShoppingItem itemToHandle) {
  List<ShoppingItem> newItems = oldItems.map((item) {
    if (item == itemToHandle) {
      return ShoppingItem(
          name: item.name, selected: item.selected, count: item.count - 1);
    } else {
      return item;
    }
  }).toList();
  // 删除数量等于0的元素
  newItems = newItems.where((item) => item.count > 0).toList();

  return newItems;
}
